<?php

	class user
	{
		/**
		 * Database object
		 */
		public $db = null;
		/**
		 * Determines if we [successfully] loaded the user
		 */
		public $loaded = null;
		/**
		 * User data
		 */
		public $data = null;
		
		public function __construct(&$db)
		{
			$this->db = &$db;
		}
		
		/**
		 * Attempts to load a user
		 */
		public function load($user)
		{
			try
			{
				// Attempt to load the user: $user
				// this query should match all information you will ever need
				$prep = $this->db->prepare('SELECT * FROM users WHERE name = ? LIMIT 0,1');
				$prep->bindParam(1, $user, PDO::PARAM_STR);
				
				if( !$prep->execute() || $prep->rowCount() === 0 )
				{
					// We didn't successfully load..
					$this->loaded = false;
				}
				else
				{
					// Notice how we didn't loaded to true yet
					$this->data($prep);
					// We have successfully loaded the user
					$this->loaded = true;
				}
			}
			catch(Exception $e)
			{
				$this->db->core->general_error_handler($e->getMessage());
			}
		}
		
		/**
		 * Remove the user from the database
		 */
		public function remove()
		{
			try
			{
				if($this->loaded)
				{
					$prep = $this->db->prepare('DELETE FROM users WHERE id = :id');
					
					if($prep->execute($this->data))
					{
						return true;
					}
					return false;
				}				
			}
			catch(Exception $e)
			{
				$this->db->core->general_error_handler($e->getMessage());
			}
		}
		
		/**
		 * Update the modifier user
		 */
		public function update($reload = false)
		{
			try
			{
				if($this->loaded)
				{
					$prep = $this->db->prepare('UPDATE users SET name = :name, password = :password WHERE id = :id');
					if($prep->execute($this->data))
					{
						if($reload)
						{
							$this->data = null;
							$this->data($prep);
						}
						return true;
					}
					return false;
				}
			}
			catch(Exception $e)
			{
				$this->db->core->general_error_handler($e->getMessage());
			}
		}
		
		/**
		 * Fetches data from result and places it in an associative array
		 * -> The array root is eliminated to leave us with just a single array
		 */
		private function data($prep)
		{
			try
			{
				// this function determines the integrity of our $data
				while($data = $prep->fetch(PDO::FETCH_ASSOC))
				{
					// Populate the data
					$this->data[] = $data;
				}
				// Remove upper array: array( [this is being removed] => array( [we are here] ) )
				$this->data = $this->data[0];
			}
			catch(Exception $e)
			{
				$this->db->core->general_error_handler($e->getMessage());
			}
		}
		
		/**
		 * Get data from array
		 */
		public function __get($what)
		{
			return $this->data[$what];
		}
		
		/**
		 * Add data to array
		 */
		public function __set($what, $value)
		{
			$this->data[$what] = $value;
		}
	}

?>